import React, { useEffect, useRef, useState } from 'react'

interface LogEntry {
  timestamp: Date
  level: 'info' | 'warn' | 'error' | 'debug'
  message: string
  data?: any
}

interface LogViewerProps {
  logs: LogEntry[]
  maxHeight?: string
  autoScroll?: boolean
  showTimestamp?: boolean
  showLevel?: boolean
  className?: string
}

const LogViewer: React.FC<LogViewerProps> = ({
  logs,
  maxHeight = '400px',
  autoScroll = false,
  showTimestamp = true,
  showLevel = true,
  className = ''
}) => {
  const logContainerRef = useRef<HTMLDivElement>(null)
  const [isUserScrolling, setIsUserScrolling] = useState(false)
  const [scrollTimeout, setScrollTimeout] = useState<NodeJS.Timeout | null>(null)

  // 自动滚动到底部
  useEffect(() => {
    if (autoScroll && !isUserScrolling && logContainerRef.current) {
      logContainerRef.current.scrollTop = 0
    }
  }, [logs, autoScroll, isUserScrolling])

  // 处理用户滚动
  const handleScroll = () => {
    if (!logContainerRef.current) return

    const { scrollTop, scrollHeight, clientHeight } = logContainerRef.current
    const isAtBottom = scrollTop + clientHeight >= scrollHeight - 10

    if (!isAtBottom) {
      setIsUserScrolling(true)
      
      // 清除之前的定时器
      if (scrollTimeout) {
        clearTimeout(scrollTimeout)
      }
      
      // 3秒后恢复自动滚动
      const timeout = setTimeout(() => {
        setIsUserScrolling(false)
      }, 3000)
      
      setScrollTimeout(timeout)
    } else {
      setIsUserScrolling(false)
    }
  }

  // 获取日志级别的样式
  const getLevelStyle = (level: string) => {
    switch (level) {
      case 'error':
        return 'text-red-600 bg-red-50'
      case 'warn':
        return 'text-yellow-600 bg-yellow-50'
      case 'info':
        return 'text-blue-600 bg-blue-50'
      case 'debug':
        return 'text-gray-600 bg-gray-50'
      default:
        return 'text-gray-600 bg-gray-50'
    }
  }

  // 获取日志级别的图标
  const getLevelIcon = (level: string) => {
    switch (level) {
      case 'error':
        return '❌'
      case 'warn':
        return '⚠️'
      case 'info':
        return 'ℹ️'
      case 'debug':
        return '🔍'
      default:
        return '📝'
    }
  }

  // 格式化时间
  const formatTimestamp = (timestamp: Date) => {
    const date = new Date(timestamp)
    const timeString = date.toLocaleTimeString('zh-CN', {
      hour12: false,
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    })
    const milliseconds = date.getMilliseconds().toString().padStart(3, '0')
    return `${timeString}.${milliseconds}`
  }

  // 滚动到底部
  const scrollToBottom = () => {
    if (logContainerRef.current) {
      logContainerRef.current.scrollTop = logContainerRef.current.scrollHeight
      setIsUserScrolling(false)
    }
  }

  // 清空日志
  const clearLogs = () => {
    // 这个功能需要父组件支持
    console.log('清空日志功能需要父组件实现')
  }

  return (
    <div className={`bg-white border border-gray-200 rounded-lg ${className}`}>
      {/* 工具栏 */}
      <div className="flex items-center justify-between px-4 py-2 border-b border-gray-200 bg-gray-50">
        <div className="flex items-center space-x-2">
          <span className="text-sm font-medium text-gray-700">运行日志</span>
          <span className="text-xs text-gray-500">({logs.length} 条)</span>
        </div>
        
        <div className="flex items-center space-x-2">
          {isUserScrolling && (
            <button
              onClick={scrollToBottom}
              className="text-xs px-2 py-1 bg-blue-100 text-blue-600 rounded hover:bg-blue-200 transition-colors"
            >
              滚动到底部
            </button>
          )}
          
          <button
            onClick={clearLogs}
            className="text-xs px-2 py-1 bg-gray-100 text-gray-600 rounded hover:bg-gray-200 transition-colors"
          >
            清空
          </button>
        </div>
      </div>

      {/* 日志内容 */}
      <div
        ref={logContainerRef}
        className="overflow-y-auto font-mono text-sm"
        style={{ maxHeight }}
        onScroll={handleScroll}
      >
        {logs.length === 0 ? (
          <div className="p-4 text-center text-gray-500">
            暂无日志
          </div>
        ) : (
          <div className="p-2 space-y-1">
            {logs.map((log, index) => (
              <div
                key={index}
                className={`flex items-start space-x-2 p-2 rounded text-xs ${getLevelStyle(log.level)}`}
              >
                {/* 级别图标 */}
                {showLevel && (
                  <span className="flex-shrink-0 w-4 text-center">
                    {getLevelIcon(log.level)}
                  </span>
                )}

                {/* 时间戳 */}
                {showTimestamp && (
                  <span className="flex-shrink-0 text-gray-500 w-20">
                    {formatTimestamp(log.timestamp)}
                  </span>
                )}

                {/* 消息内容 */}
                <div className="flex-1 min-w-0">
                  <div className="break-words">{log.message}</div>
                  
                  {/* 额外数据 */}
                  {log.data && (
                    <div className="mt-1 text-xs text-gray-600">
                      <pre className="whitespace-pre-wrap">
                        {typeof log.data === 'string' ? log.data : JSON.stringify(log.data, null, 2)}
                      </pre>
                    </div>
                  )}
                </div>
              </div>
            ))}
          </div>
        )}
      </div>

      {/* 底部状态栏 */}
      {isUserScrolling && (
        <div className="px-4 py-2 border-t border-gray-200 bg-yellow-50">
          <div className="flex items-center space-x-2 text-xs text-yellow-700">
            <span>⏸️</span>
            <span>自动滚动已暂停，有新日志时不会自动滚动到底部</span>
          </div>
        </div>
      )}
    </div>
  )
}

export default LogViewer
